<template>
  <section class="todoapp">
    <hm-header @add='handleAdd'></hm-header>
    <hm-main :list='showList' @del='handleDel' @changeState='handleChangestate' @changeAll='changeAll'></hm-main>
    <hm-footer :list='list' @clear='handleClear' :type='type' @changeType='changeType'></hm-footer>
  </section>
</template>

<script>
import HmHeader from './components/hm-header.vue'
import HmMain from './components/hm-main.vue'
import HmFooter from './components/hm-footer.vue'
export default {
  components: {
    HmHeader,
    HmMain,
    HmFooter
  },
  data () {
  return {
   list: JSON.parse(localStorage.getItem('todoList'))||[],
    type:'all'
  }
},
methods:{
  changeAll(flag) {
    this.list.forEach(item=>item.isDone=flag)
  },
  handleDel(id) {
    const index=this.list.findIndex(item=>item.id===id)
    this.list.splice(index,1)
  },
  handleAdd(todoName) {
    this.list.unshift({
      id:+new Date(),
      name:todoName,
      isDone:false
    })
  },
handleChangestate(flag,id) {
  const obj=this.list.find(item=>item.id===id)
  obj.isDone=flag
},
handleClear() {
  // 把所有未完成的筛选出来并保留  filter筛选出符合条件的并保留
  this.list=this.list.filter(item=>item.isDone===false)
},
changeType(type) {
  this.type=type
}
},
computed:{
  showList() {
    if(this.type==='all') {
      return this.list
    } else if(this.type==='active') {
      // 未完成
      return this.list.filter(item=>item.isDone===false)
    } else {
      // 已完成
      return this.list.filter(item=>item.isDone===true)
    }
  }
},
watch:{
  list:{
    deep:true,
    handler(newVal) {
      localStorage.setItem('todoList',JSON.stringify(newVal))
    }
  }
},
}
</script>

<style></style>
